export function listToTreeOption(list, cb) {
  const cache = {}
  const options = []
  const missing = {}

  list.forEach((item) => {
    const { parentId, id, label, value, normal } = cb(item)
    const parent = cache[parentId]
    const children = {
      label,
      value,
      disabled: normal === 1 ? false : true,
    }
    cache[id] = children

    if (parentId === 0) {
      options.push(children)
    } else if (parent) {
      parent.children = parent.children || []
      parent.children.push(children)
    } else {
      missing[parentId] = children
    }
  })

  // 兜底
  Object.entries(missing).forEach(([parentId, children]) => {
    const parent = cache[parentId]

    if (parent) {
      parent.children = parent.children || []
      parent.children.push(children)
    }
  })

  return options
}

/**
 * 编码
 *
 * @param {Object} obj 对象
 */
export function encode(obj) {
  return encodeURIComponent(JSON.stringify(obj))
}

/**
 * 解码
 *
 * @param {Object} obj 对象
 */
export function decode(obj) {
  return JSON.parse(decodeURIComponent(obj))
}

/**
 * 空对象
 *
 * @param {Any} obj 需判断的值
 */
export function isEmptyObject(obj) {
  return (
    typeof obj === 'object' && (obj === null || Object.keys(obj).length === 0)
  )
}
